package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @RequestMapping("/page")
    public String page(Model model,
                       SysUser condition,
                       @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        Page<SysUser> page=null;
        try{
            page=sysUserService.findPage(condition,pageNo,pageSize);
            List<SysRole>roleList=sysRoleService.findAll();

            model.addAttribute("pageInfo",page);
            model.addAttribute("roleList",roleList);
            model.addAttribute("condition",condition);
        }catch (Exception e){
            LOGGER.error("SysUserController中的page方法执行错误.",e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;

    @GetMapping("/save")
    public String toSave(Model model){
        List<SysRole>roleList=null;
        try{
            roleList=sysRoleService.findAll();
            model.addAttribute("roleList",roleList);
            model.addAttribute("sysUser",new SysUser());
        }catch (Exception e){
            LOGGER.error("SysUserController中的toSave方法执行错误",e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }


    @PostMapping("/save")
    public String doSave(SysUser sysUser,
                         @RequestParam("idPic") MultipartFile idPic,
                         @RequestParam("workPic") MultipartFile workPic){
        String[] allowImageExt={"jpg","jpeg","png","gif","bmp"};
        try{
            if(idPic!=null){
                String idPicPath= uploadService.uploadFile(idPic,allowImageExt);
                sysUser.setIdPicPath(idPicPath);
            }
            if(workPic!=null){
                String workPicPath=uploadService.uploadFile(workPic,allowImageExt);
                sysUser.setWorkPicPath(workPicPath);
            }

            SysUser loginUser=session(Constants.SESSION_USER);
            if(sysUser.getId()==null){
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
            }else {
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
            }
            boolean ok=sysUserService.saveOrUpdate(sysUser);
            if(ok){
                return redirect("/main/user/page");
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的doSave方法执行错误",e);
        }
        return "user/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model) {
        SysUser sysUser = null;
        try {
            sysUser = sysUserService.findById(id);
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "user/view";
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id,Model model){
        SysUser sysUser=null;
        List<SysRole> roleList=null;
        try{
            sysUser=sysUserService.findById(id);
            roleList=sysRoleService.findAll();
            model.addAttribute("roleList",roleList);
            model.addAttribute("sysUser",sysUser);
        }catch (Exception e){
            LOGGER.error("SysUserController中的toEdit方法发生错误.",e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @ResponseBody
    @GetMapping("/accountExist")
    public String accountExist(@RequestParam("account") String account){
        LOGGER.error("检查用户名account={}的用户是否存在",account);
        HashMap<String,Object> resultMap=new HashMap<String ,Object>();
        if (StringUtils.isEmpty(account)){
            resultMap.put("exist",0);
        }else {
            try {
                SysUser sysUser=sysUserService.findByAccount(account);
                if (null!=sysUser){
                    resultMap.put("exist",1);
                }else {
                    resultMap.put("exist",0);
                }
            }catch (Exception e){
                LOGGER.error("SysUserController中的"+"accountExists方法执行发生错误。",e);
                resultMap.put("error","出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @GetMapping("/{id}/view")
    public String ajaxView(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            SysUser sysUser = sysUserService.findById(id);
            if (sysUser != null) {
                map.put("code", 200);
                map.put("data", sysUser);
            } else {
                map.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController中的ajaxView方法执行发生错误。 ", e);
            map.put("code", 500);
        }
        return JSON.toJSONString(map);
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Integer id, Model model) {
        Map<String, Object> map = new HashMap<>();
        try {
            boolean num = sysUserService.delete(id);
            if (num) {
                map.put("code", 200);
                map.put("msg", "删除成功");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return map;
    }
}
